#!/usr/bin/env perl
 
# 
# Copyright (c) 2002-2007 Eric Wallengren
# This file is part of the Continuous Automated Build and Integration 
# Environment (CABIE)
# 
# CABIE is distributed under the terms of the GNU General Public
# License version 2 or any later version.  See the file COPYING for copying 
# permission or http://www.gnu.org. 
#                                                                            
# THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED OR  
# IMPLIED, without even the implied warranty of MERCHANTABILITY or FITNESS 
# FOR A PARTICULAR PURPOSE.  ANY USE IS AT YOUR OWN RISK. 
#                                                                            
# Permission to modify the code and to distribute modified code is granted, 
# provided the above notices are retained, and a notice that the code was 
# modified is included with the above copyright notice. 
# 

use strict;
no  strict "refs";

#
# The buildserver needs to be handled differently
# on a non-posix system (Windows)
#
my $POSIX = 1;

my $ospackage;

#
# See if this is a windoz system...
#
if ($ =~ /MSWin32/) {
    $POSIX = 0;
    $ospackage  = "winsys";
} else {
    $ospackage  = "unixsys";
}

use Cwd;

my $dir = cwd();

use Sys::Hostname;
use File::Copy;
use File::Path;
use IO::Handle;
use Mail::Sendmail;

BEGIN{push @INC, "lib";}

my $hostname     = hostname();
$hostname        =~ s/\.[a-zA-Z0-9]+//g;

my $configname   = $hostname;
$configname      =~ s/-//g;

#
# Load master configuration file
#
require "$configname.pm";

#
# Create instances of packages enabled above...
#
my $config = new $configname;

#
# unixsys for posix
# winsys for windows
#
require "$ospackage.pm";

#
# Create instances of packages enabled above...
# unixsys for posix
# winsys for windows
#
my $os  = new $ospackage;

my $Source    = $ARGV[0];
my $Target    = $ARGV[1];
my $BuildName = $ARGV[2];
my $JobNo     = $ARGV[3];

copyfiles();

sub copyfiles {

    my $pid;

    my $entry;
    my $bFailed = 0;

    my @platforms = qw (hpux 
                        linux 
                        windows
                        solaris);
    my @failedimage;

    #
    # Call forkprocess and wait for completion
    #
    if ( $POSIX) {
        $pid = $os->forkprocess("cp -r $Source/* $Target", 1, 0);
    } else {
        $Source    =~ s/[\/]/\\/g;
        $Target    =~ s/[\/]/\\/g;
        $pid = $os->forkprocess("xcopy $Source $Target /i/s/y", 1, 0);
    }

    if ($pid != 0) {
        notify(1, "Copy of $Source to $Target may have failed");
    }

    foreach $entry (@platforms) {
        chomp $entry;
        $pid = $os->forkprocess("java -jar ~/verifychecksums.jar -1 ".
                                "$Source/image/$entry $Target/image/$entry",
                                1, 0);
        if ($pid) {
            push @failedimage, $entry;
            $bFailed = 1;
        }
    }

    if ($bFailed) {
        notify(1, "Checksums for @failedimage failed");
    } else {
        notify(0, "Build Promotion Completed");
    }


}

sub notify {

    my $bad = shift;
    my $msg = shift;

    my $smtp  = $config->SMTP;
    my $admin = $config->ADMIN;
    my $delim = $config->SMTPDELIM;

    my $sqlline;
    my $sqlquery;
    my @queryarray;

    my $hashkey;

    my %mail;
    my %tohash;

    $mail{"Smtp"} = $smtp;
    $mail{"From"} = "Build Promotion <$admin>";
    
    #
    # Gather up address and put them into a hash to eliminate
    # duplicate entries.
    #
    $sqlquery  = "select address from subscription where binary ".
                 "server=\"$hostname\" and binary ".
                 "title=\"$BuildName\"";

    @queryarray = $os->run_sql_query("$sqlquery", ";", 0);

    #
    # See if there's an email file for promotions only
    #
    if ( -f "./promote.email") {
        open (EMAIL, "<./promote.email");
        while (<EMAIL>) {
            chomp $_;
            if ($_ !~ /^[#\n\t\ ]/) {
                push @queryarray, "$_";
            }
        }
        close(EMAIL);
    }

    foreach $sqlline(@queryarray) {
        chomp $sqlline;
        $tohash{"$sqlline"} = "";
    }

    $Target =~ s/\\/\//g;

    #
    # The email will, at least, get sent to the build administrator
    #
    $tohash{"$admin"} = "";
    
    if ($bad) {
        $mail{Subject}    = "*$BuildName $JobNo failed to copy*";
        $mail{Message}    = "The error reported is as follows:\n\n".
                            "$msg\n";
    } else {
        $mail{Subject}    = "*$BuildName $JobNo promoted for testing*";
        $mail{Message}    = "$BuildName $JobNo was promoted to ".
                            "$Target and is available for testing\n";
    }

    foreach $hashkey (keys %tohash) {
        $mail{To} .= "$hashkey$delim";
    }

    sendmail %mail;

    if ($bad) {
        exit 1;
    }

    exit 0;

}
